import { Request, Response } from 'express';
import { dictionaryService } from '../services/dictionary-service';
import { ResponseUtil } from '../utils/response';
import {
  CreateDictionaryRequest,
  UpdateDictionaryRequest,
  CreateDictionaryItemRequest,
  UpdateDictionaryItemRequest,
  DictionaryQueryParams,
  DictionaryItemQueryParams,
} from '../models/Dictionary';

export class DictionaryController {
  // 字典管理
  async createDictionary(req: Request, res: Response) {
    try {
      const data: CreateDictionaryRequest = req.body;

      // 验证必填字段
      if (!data.code || !data.name) {
        return ResponseUtil.badRequest(res, '字典编码和名称不能为空');
      }

      const dictionary = await dictionaryService.createDictionary(data);
      return ResponseUtil.success(res, dictionary, '字典创建成功');
    } catch (error: any) {
      if (error.code === 'P2002') {
        return ResponseUtil.badRequest(res, '字典编码已存在');
      }
      return ResponseUtil.error(res, error.message || '创建字典失败', 500);
    }
  }

  async updateDictionary(req: Request, res: Response) {
    try {
      const { id } = req.params;
      const data: UpdateDictionaryRequest = req.body;

      const dictionary = await dictionaryService.updateDictionary(id, data);
      return ResponseUtil.success(res, dictionary, '字典更新成功');
    } catch (error: any) {
      if (error.code === 'P2025') {
        return ResponseUtil.notFound(res, '字典不存在');
      }
      return ResponseUtil.error(res, error.message || '更新字典失败', 500);
    }
  }

  async deleteDictionary(req: Request, res: Response) {
    try {
      const { id } = req.params;
      await dictionaryService.deleteDictionary(id);
      return ResponseUtil.success(res, null, '字典删除成功');
    } catch (error: any) {
      if (error.code === 'P2025') {
        return ResponseUtil.notFound(res, '字典不存在');
      }
      return ResponseUtil.error(res, error.message || '删除字典失败', 500);
    }
  }

  async getDictionaryById(req: Request, res: Response) {
    try {
      const { id } = req.params;
      const dictionary = await dictionaryService.getDictionaryById(id);

      if (!dictionary) {
        return ResponseUtil.notFound(res, '字典不存在');
      }

      return ResponseUtil.success(res, dictionary);
    } catch (error: any) {
      return ResponseUtil.error(res, error.message || '获取字典失败', 500);
    }
  }

  async getDictionaryByCode(req: Request, res: Response) {
    try {
      const { code } = req.params;
      const dictionary = await dictionaryService.getDictionaryByCode(code);

      if (!dictionary) {
        return ResponseUtil.notFound(res, '字典不存在');
      }

      return ResponseUtil.success(res, dictionary);
    } catch (error: any) {
      return ResponseUtil.error(res, error.message || '获取字典失败', 500);
    }
  }

  async getDictionaries(req: Request, res: Response) {
    try {
      const params: DictionaryQueryParams = {
        page: parseInt(req.query.page as string) || 1,
        pageSize: parseInt(req.query.pageSize as string) || 10,
        code: req.query.code as string,
        name: req.query.name as string,
        status: req.query.status
          ? parseInt(req.query.status as string)
          : undefined,
      };

      const result = await dictionaryService.getDictionaries(params);
      return ResponseUtil.success(res, result);
    } catch (error: any) {
      return ResponseUtil.error(res, error.message || '获取字典列表失败', 500);
    }
  }

  // 字典项管理
  async createDictionaryItem(req: Request, res: Response) {
    try {
      const data: CreateDictionaryItemRequest = req.body;

      // 验证必填字段
      if (!data.dictionaryId || !data.label || !data.value) {
        return ResponseUtil.badRequest(res, '字典ID、编码、标签和值不能为空');
      }

      const item = await dictionaryService.createDictionaryItem(data);
      return ResponseUtil.success(res, item, '字典项创建成功');
    } catch (error: any) {
      if (error.code === 'P2002') {
        return ResponseUtil.badRequest(res, '该字典下编码已存在');
      }
      if (error.code === 'P2003') {
        return ResponseUtil.badRequest(res, '字典不存在');
      }
      return ResponseUtil.error(res, error.message || '创建字典项失败', 500);
    }
  }

  async updateDictionaryItem(req: Request, res: Response) {
    try {
      const { id } = req.params;
      const data: UpdateDictionaryItemRequest = req.body;

      const item = await dictionaryService.updateDictionaryItem(id, data);
      return ResponseUtil.success(res, item, '字典项更新成功');
    } catch (error: any) {
      if (error.code === 'P2025') {
        return ResponseUtil.notFound(res, '字典项不存在');
      }
      if (error.code === 'P2002') {
        return ResponseUtil.badRequest(res, '该字典下编码已存在');
      }
      return ResponseUtil.error(res, error.message || '更新字典项失败', 500);
    }
  }

  async deleteDictionaryItem(req: Request, res: Response) {
    try {
      const { id } = req.params;
      await dictionaryService.deleteDictionaryItem(id);
      return ResponseUtil.success(res, null, '字典项删除成功');
    } catch (error: any) {
      if (error.code === 'P2025') {
        return ResponseUtil.notFound(res, '字典项不存在');
      }
      return ResponseUtil.error(res, error.message || '删除字典项失败', 500);
    }
  }

  async getDictionaryItemById(req: Request, res: Response) {
    try {
      const { id } = req.params;
      const item = await dictionaryService.getDictionaryItemById(id);

      if (!item) {
        return ResponseUtil.notFound(res, '字典项不存在');
      }

      return ResponseUtil.success(res, item);
    } catch (error: any) {
      return ResponseUtil.error(res, error.message || '获取字典项失败', 500);
    }
  }

  async getDictionaryItems(req: Request, res: Response) {
    try {
      const params: DictionaryItemQueryParams = {
        page: parseInt(req.query.page as string) || 1,
        pageSize: parseInt(req.query.pageSize as string) || 10,
        dictionaryId: req.query.dictionaryId as string,
        label: req.query.label as string,
        status: req.query.status
          ? parseInt(req.query.status as string)
          : undefined,
        parentId: req.query.parentId as string,
      };

      const result = await dictionaryService.getDictionaryItems(params);
      return ResponseUtil.success(res, result);
    } catch (error: any) {
      return ResponseUtil.error(
        res,
        error.message || '获取字典项列表失败',
        500
      );
    }
  }

  async getDictionaryItemsByCode(req: Request, res: Response) {
    try {
      const { code } = req.params;
      const items =
        await dictionaryService.getDictionaryItemsByDictionaryCode(code);
      return ResponseUtil.success(res, items);
    } catch (error: any) {
      return ResponseUtil.error(res, error.message || '获取字典项失败', 500);
    }
  }

  // 批量操作
  async batchUpdateDictionaryItemsSort(req: Request, res: Response) {
    try {
      const { items } = req.body;

      if (!Array.isArray(items)) {
        return ResponseUtil.badRequest(res, '参数格式错误');
      }

      await dictionaryService.batchUpdateDictionaryItemsSort(items);
      return ResponseUtil.success(res, null, '排序更新成功');
    } catch (error: any) {
      return ResponseUtil.error(res, error.message || '更新排序失败', 500);
    }
  }

  async batchUpdateDictionariesSort(req: Request, res: Response) {
    try {
      const { dictionaries } = req.body;

      if (!Array.isArray(dictionaries)) {
        return ResponseUtil.badRequest(res, '参数格式错误');
      }

      await dictionaryService.batchUpdateDictionariesSort(dictionaries);
      return ResponseUtil.success(res, null, '排序更新成功');
    } catch (error: any) {
      return ResponseUtil.error(res, error.message || '更新排序失败', 500);
    }
  }
}

export const dictionaryController = new DictionaryController();
